package cn.hxzy.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hxzy.common.OcrClient;
import cn.hxzy.common.OssUtil;
import cn.hxzy.common.Result;
import cn.hxzy.common.util.RandomId;
import cn.hxzy.entity.DrivingLicenseBack;
import cn.hxzy.entity.DrivingLicenseFace;
import cn.hxzy.entity.accreditation.TsVehicleCertification;
import cn.hxzy.entity.accreditation.vo.Vehicle;
import cn.hxzy.service.TsCarCardService;
import cn.hxzy.service.TsVehicleCertificationService;
import com.aliyun.ocr20191230.Client;
import com.aliyun.ocr20191230.models.RecognizeDrivingLicenseRequest;
import com.aliyun.ocr20191230.models.RecognizeDrivingLicenseResponse;
import com.aliyun.tea.TeaException;
import io.lettuce.core.ScriptOutputType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Kuizhi.Ma
 * @since 2023-06-25
 * 车辆行驶证认证
 */
@RestController
@CrossOrigin
@RequestMapping("/tsVehicleCertification")
public class TsVehicleCertificationController {

    @Autowired
    private TsVehicleCertificationService tsVehicleCertificationService;

    @RequestMapping("insertVehicle")
//   新增车辆认证信息
    public Result insertVehicle(@RequestBody Vehicle vehicle) throws ParseException {
        if (ObjectUtil.isEmpty(vehicle)) {
            return Result.error().code(101);
        }
        if (!vehicle.getLiplateNumber().equals(vehicle.getPlateNumber())) {
            return Result.error().code(102).message("车牌号与行驶证记录车牌号不一致，请检查后再次提交");
        }
        TsVehicleCertification tsVehicleCertification1 = tsVehicleCertificationService.selectTsVehicleCertification(vehicle.getPlateNumber());
        if (ObjectUtil.isNotEmpty(tsVehicleCertification1)) {
            return Result.error().code(103).message("车辆信息已注册，请重新填写认证信息");
        }
        //        创建车辆认证信息实例
        TsVehicleCertification tsVehicleCertification = new TsVehicleCertification();

//       注册日期-- 注册时间转换（字符串转date）
        String registerDate = vehicle.getRegisterDate();
        String substring = registerDate.substring(0, 4);
        String substring1 = registerDate.substring(4, 6);
        String substring2 = registerDate.substring(6, 8);
        String registerDates = substring + "-" + substring1 + "-" + substring2;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = sdf.parse(registerDates);
        tsVehicleCertification.setRegisterDate(parse);
//        认证ID
        String vehicleId = RandomId.getVehicleId();
        tsVehicleCertification.setAuthenticationId(vehicleId);
//        用户编号
        String driverId = RandomId.getDriverId();
        tsVehicleCertification.setUserId(driverId);
//        用户姓名
        tsVehicleCertification.setUserName(vehicle.getOwner());
//        用户手机号
        tsVehicleCertification.setRegisterPhone("17635711209");
//        住址    address
        tsVehicleCertification.setAddress(vehicle.getAddress());
//        发动机号码     engineNumber
        tsVehicleCertification.setEngineNumber(vehicle.getEngineNumber());
//        发证日期      issueDate
        String issueDate = vehicle.getIssueDate();
        String substring5 = issueDate.substring(0, 4);
        String substring4 = issueDate.substring(4, 6);
        String substring3 = issueDate.substring(6, 8);
        String issueDates = substring5 + "-" + substring4 + "-" + substring3;
        Date parse1 = sdf.parse(issueDates);
        tsVehicleCertification.setIssueDate(parse1);
//        品牌型号      model
        tsVehicleCertification.setModel(vehicle.getModel());
//        所有人       owner
        tsVehicleCertification.setOwner(vehicle.getOwner());
//        车牌号码      licensePlateNumber
        tsVehicleCertification.setPlateNumber(vehicle.getPlateNumber());
//        使用性质      useNature
        tsVehicleCertification.setUseNature(vehicle.getUseNature());
//        车辆类型      vehicleType
        tsVehicleCertification.setVehicleType(vehicle.getVehicleType());
//        车辆识别代码       vinCode
        tsVehicleCertification.setVinCode(vehicle.getVinCode());
//        签发机关      issueAuthority
        tsVehicleCertification.setIssueAuthority(vehicle.getIssueAuthority());
//        检验记录      inspectionRecord
        tsVehicleCertification.setInspectionRecord(vehicle.getInspectionRecord());
//        核定载人数     passengerCapacity
        tsVehicleCertification.setPassengerCapacity(vehicle.getPassengerCapacity());
//        总质量       totalWeight
        tsVehicleCertification.setTotalWeight(vehicle.getTotalWeight());
//        整备质量      curbWeight
        tsVehicleCertification.setCurbWeight(vehicle.getCurbWeight());
//        核定载质量     permittedWeight
        tsVehicleCertification.setPermittedWeight(vehicle.getPermittedWeight());
//        外廓尺寸      overallDimension
        tsVehicleCertification.setOverallDimension(vehicle.getOverallDimension());
//        准牵引总质量        tractionWeight
        tsVehicleCertification.setTractionWeight(vehicle.getTractionWeight());
//        能源标志      energySign
        tsVehicleCertification.setEnergySign(vehicle.getEnergySign());
//        档案编号      recordNumber
        tsVehicleCertification.setRecordNumber(vehicle.getRecordNumber());
//        备注        remarks
        tsVehicleCertification.setRemarks(vehicle.getRemarks());
//        条形码编号     barcodeNumber
        tsVehicleCertification.setBarcodeNumber(vehicle.getBarcodeNumber());
//        道路运输证号        transportCertificate
        tsVehicleCertification.setTransportCertificate(vehicle.getTransportCertificate());
//        道路运输经营许可证     transportationBusinessLicense
        tsVehicleCertification.setTransportationBusinessLicense(vehicle.getTransportationBusinessLicense());
//        中交入网      networkAccess
        tsVehicleCertification.setNetworkAccess(vehicle.getNetworkAccess());
//        卸车类型      unloadingType
        if (vehicle.getUnloadingType().equals(1)) {
            tsVehicleCertification.setUnloadingType("自卸");
        } else {
            tsVehicleCertification.setUnloadingType("半自卸");
        }
//        执行新增车辆信息
        TsVehicleCertification tsVehicle = tsVehicleCertificationService.insertTsVehicleCertification(tsVehicleCertification);
        return Result.ok().data1(tsVehicle);
    }

    @RequestMapping("getVehicleFace")
//    上传行驶证正面
    public Result getVehicleFace(@RequestParam MultipartFile file) {
        //        调用工具类返回的图片路径
        String ossUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_IMAGES);
        //        OCR验证的客户端
        Client client = OcrClient.getOCRClient();
        DrivingLicenseFace drivingLicenseFace = recognizeDrivingLicenseFace(client, ossUrl);
        drivingLicenseFace.setTravelCardFront( ossUrl.substring(67));
        return Result.ok().data1(drivingLicenseFace);
    }

    @RequestMapping("getVehicleBack")
//    上传行驶证反面
    public Result getVehicleBack(@RequestParam MultipartFile file) {
        //        调用工具类返回的图片路径
        String ossUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_IMAGES);
        //        OCR验证的客户端
        Client client = OcrClient.getOCRClient();
        DrivingLicenseBack drivingLicenseBack = recognizeDrivingLicenseBack(client, ossUrl);
        drivingLicenseBack.setTravelCardOpposite( ossUrl.substring(67));
        return Result.ok().data1(drivingLicenseBack);
    }

    @RequestMapping("getTransport")
//    道路运输上传
    public Result getTransport(@RequestParam MultipartFile file) {
        //        调用工具类返回的图片路径
        String ossUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_IMAGES);
        //        OCR验证的客户端
        Client client = OcrClient.getOCRClient();

        return Result.ok().data1( ossUrl.substring(67));
    }

    @RequestMapping("getPermission")
//    道路许可上传
    public Result getPermission(@RequestParam MultipartFile file) {
        //        调用工具类返回的图片路径
        String ossUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_IMAGES);
        //        OCR验证的客户端
        Client client = OcrClient.getOCRClient();
        return Result.ok().data1( ossUrl.substring(67));
    }

    @RequestMapping("getBuyCar")
//    购车合同上传
    public Result getBuyCar(@RequestParam MultipartFile file) {
        //        调用工具类返回的图片路径
        String ossUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_IMAGES);
        //        OCR验证的客户端
        Client client = OcrClient.getOCRClient();
        return Result.ok().data1( ossUrl.substring(67));
    }

    @RequestMapping("getRentCar")
//    租车合同上传
    public Result getRentCar(@RequestParam MultipartFile file) {
        //        调用工具类返回的图片路径
        String ossUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_IMAGES);
        //        OCR验证的客户端
        Client client = OcrClient.getOCRClient();
        return Result.ok().data1( ossUrl.substring(67));
    }

    @RequestMapping("getCompulsory")
//    交强险上传
    public Result getCompulsory(@RequestParam MultipartFile file) {
        //        调用工具类返回的图片路径
        String ossUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_IMAGES);
        //        OCR验证的客户端
        Client client = OcrClient.getOCRClient();
        return Result.ok().data1( ossUrl.substring(67));
    }

    @RequestMapping("getManCar")
//    人车合照上传
    public Result getManCar(@RequestParam MultipartFile file) {
        //        调用工具类返回的图片路径
        String ossUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_IMAGES);
        //        OCR验证的客户端
        Client client = OcrClient.getOCRClient();
        return Result.ok().data1( ossUrl.substring(67));
    }

    //    行驶证正面
    private static DrivingLicenseFace recognizeDrivingLicenseFace(Client client, String ossUrl) {
        //face是正面，back是背面，我们一般用正面就行，这个可以传过来的
        RecognizeDrivingLicenseRequest request = new RecognizeDrivingLicenseRequest()
                .setImageURL(ossUrl)
                .setSide("face");
        DrivingLicenseFace drivingLicenseFace = new DrivingLicenseFace();
        try {
            // 复制代码运行请自行打印 API 的返回值
            RecognizeDrivingLicenseResponse recognizeDrivingLicenseResponse = client.recognizeDrivingLicense(request);
//            住址
            drivingLicenseFace.setAddress(recognizeDrivingLicenseResponse.getBody().getData().getFaceResult().address);
//            发动机号码
            drivingLicenseFace.setEngineNumber(recognizeDrivingLicenseResponse.getBody().getData().getFaceResult().engineNumber);
//            发证日期
            drivingLicenseFace.setIssueDate(recognizeDrivingLicenseResponse.getBody().getData().getFaceResult().issueDate);
//            品牌型号
            drivingLicenseFace.setModel(recognizeDrivingLicenseResponse.getBody().getData().getFaceResult().model);
//            所有人
            drivingLicenseFace.setOwner(recognizeDrivingLicenseResponse.getBody().getData().getFaceResult().owner);
//            车牌号
            drivingLicenseFace.setPlateNumber(recognizeDrivingLicenseResponse.getBody().getData().getFaceResult().plateNumber);
//            注册日期
            drivingLicenseFace.setRegisterDate(recognizeDrivingLicenseResponse.getBody().getData().getFaceResult().registerDate);
//            使用性质（非营运）
            drivingLicenseFace.setUseCharacter(recognizeDrivingLicenseResponse.getBody().getData().getFaceResult().useCharacter);
//            车辆类型
            drivingLicenseFace.setVehicleType(recognizeDrivingLicenseResponse.getBody().getData().getFaceResult().vehicleType);
//            车辆识别代号
            drivingLicenseFace.setVin(recognizeDrivingLicenseResponse.getBody().getData().getFaceResult().vin);
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            System.out.println(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            System.out.println(error.message);
        }
        return drivingLicenseFace;
    }

    //    行驶证反面
    private static DrivingLicenseBack recognizeDrivingLicenseBack(Client client, String ossUrl) {
        //face是正面，back是背面，我们一般用正面就行，这个可以传过来的
        RecognizeDrivingLicenseRequest request = new RecognizeDrivingLicenseRequest()
                .setImageURL(ossUrl)
                .setSide("back");
        DrivingLicenseBack drivingLicenseBack = new DrivingLicenseBack();
        try {
            // 复制代码运行请自行打印 API 的返回值
            RecognizeDrivingLicenseResponse recognizeDrivingLicenseResponse = client.recognizeDrivingLicense(request);

            drivingLicenseBack.setApprovedLoad(recognizeDrivingLicenseResponse.getBody().getData().getBackResult().approvedLoad);
//            核定载人数
            drivingLicenseBack.setApprovedPassengerCapacity(recognizeDrivingLicenseResponse.getBody().getData().getBackResult().approvedPassengerCapacity);
//            检验记录
            drivingLicenseBack.setEnergyType(recognizeDrivingLicenseResponse.getBody().getData().getBackResult().energyType);
            drivingLicenseBack.setFileNumber(recognizeDrivingLicenseResponse.getBody().getData().getBackResult().fileNumber);
//            总质量
            drivingLicenseBack.setGrossMass(recognizeDrivingLicenseResponse.getBody().getData().getBackResult().grossMass);
//            检验记录
            drivingLicenseBack.setInspectionRecord(recognizeDrivingLicenseResponse.getBody().getData().getBackResult().inspectionRecord);
//            外部尺寸
            drivingLicenseBack.setOverallDimension(recognizeDrivingLicenseResponse.getBody().getData().getBackResult().overallDimension);
//            车牌号
            drivingLicenseBack.setPlateNumber(recognizeDrivingLicenseResponse.getBody().getData().getBackResult().plateNumber);
//
            drivingLicenseBack.setTractionMass(recognizeDrivingLicenseResponse.getBody().getData().getBackResult().tractionMass);
//            整备质量
            drivingLicenseBack.setUnladenMass(recognizeDrivingLicenseResponse.getBody().getData().getBackResult().unladenMass);
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            System.out.println(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            System.out.println(error.message);
        }
        return drivingLicenseBack;
    }

}

